#include <iostream>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
 
const int size = 1024;
 
 
// 子进程进行读
void SonRead(int wfd)
{
    char inbuffer[size];
    while (true)
    {
        ssize_t n = read(wfd, inbuffer, sizeof(inbuffer) - 1);
 
        if (n > 0)
        {
            inbuffer[n] = 0; // =='0'
            std::cout << "son get message: " << inbuffer << std::endl;
        }
    }
}
 
void FatherWrite(int wfd)
{
 
    std::string message = "i am father!";
    while (true)
    {
 
        write(wfd, message.c_str(), message.size()); // 写入管道的时候没有写入\0因为没有必要
 
        sleep(3); // 让父进程写的慢一点，保证读端比写端块
    }
}
 
// 父进程进行读取
 
int main()
{
    // 创建管道
    int pipefd[2];
    int n = pipe(pipefd);
 
    if (n != 0)
    {
        std::cerr << "errno: " << errno << ": " << "errstring : " << strerror(errno) << std::endl;
        return 1;
    }
 
    // 创建子进程:
    pid_t id = fork();
    if (id == 0)
    {
        std::cout << "子进程关闭不需要的fd, 准备通信: 收消息: " << std::endl;
        sleep(1);
 
        // 子进程 --- read
        close(pipefd[1]);
 
        SonRead(pipefd[0]);
 
        close(pipefd[0]); // 不再通信时关闭，也可以不关
        exit(0);
    }
 
    // 父进程 --- read
 
    std::cout << "父进程关闭不需要的fd, 准备通信: 写消息" << std::endl;
    sleep(1);
    // 关闭不需要的fd:
    close(pipefd[0]);
 
    FatherWrite(pipefd[1]);
 
    close(pipefd[1]); 
 
    pid_t rid = waitpid(id, nullptr, 0);
    if (rid > 0)
    {
        std::cout << "wait child process done!" << std::endl;
    }
 
    return 0;
}